package com.client;

import com.config.GrpcProperties;
import com.meta.HtMetaInfoSyncServiceGrpc;
import com.meta.HtMetaSyncRequest;
import com.meta.HtMetaSyncResponse;
import com.meta.SyncType;
import io.grpc.ManagedChannel;
import io.grpc.StatusRuntimeException;
import io.grpc.netty.NettyChannelBuilder;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author xiaoshu
 */
@Component
public class HtMetaInfoSyncClient {

    @Resource
    private GrpcProperties grpcProperties;

    @SneakyThrows
    public String syncMeta(final String json,final SyncType syncType) {
        ManagedChannel channel = null;
        try {
            channel=NettyChannelBuilder.
                    forAddress(grpcProperties.getServerIp(),grpcProperties.getPort())
                    //非加密连接
                    .usePlaintext()
                    //加密
                    //.sslContext(grpcProperties.buildClentSslContext())
                    .build();
            HtMetaInfoSyncServiceGrpc.HtMetaInfoSyncServiceBlockingStub stub = HtMetaInfoSyncServiceGrpc.newBlockingStub(channel);
            HtMetaSyncResponse htMetaSyncResponse = stub.syncMeta((
                    HtMetaSyncRequest.newBuilder()
                            .setSyncJson(json)
                            .setSyncType(syncType)
                            .build()));
            String code = htMetaSyncResponse.getCode();
            String msg = htMetaSyncResponse.getMsg();
            return code+":"+msg;
        } catch (final StatusRuntimeException e) {
            return "FAILED with " + e.getStatus().getCode().name();
        }finally {
            if (Objects.nonNull(channel)){
                channel.shutdown();
            }
        }
    }
}